package com.atguigu.exam.service.impl;

import com.atguigu.exam.entity.Banner;
import com.atguigu.exam.mapper.BannerMapper;
import com.atguigu.exam.service.BannerService;

import com.atguigu.exam.service.FileUploadService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 轮播图服务实现类
 */
@Service
public class BannerServiceImpl extends ServiceImpl<BannerMapper, Banner> implements BannerService {
    @Autowired
    private FileUploadService fileUploadService;
    @Override
    public String uploadBannerImage(MultipartFile file) throws Exception {
        //1.非空校验
        if (file==null || file.isEmpty()){
            throw new RuntimeException("上传轮播图图片失败，原因：上传的文件为空");
        }
        //2.格式校验
        if(!file.getContentType().startsWith("image")){
            throw new RuntimeException("上传轮播图图片失败，原因：上传的文件类型错误");
        }
        //3.调用核心业务
        String url = fileUploadService.uploadFile("banners",file);
        //4.返回地址
        return url;
    }

    /**
     * 保存轮播图信息
     * @param banner
     * @Param banner 轮播图信息对象
     */
    @Override
    public void addBanner(Banner banner) throws Exception {
        //1.检查默认值
        if (banner.getIsActive()==null){
            banner.setIsActive(true);
        }
        if (banner.getSortOrder()==null){
            banner.setSortOrder(5);
        }
        //2.自动填充字段 createTime updateTime is_deleted
        //3.保存banner
        boolean result = save(banner);
        if (!result){
            throw new Exception("轮播图数据保存失败");
        }
    }

    /**
     * 更新轮播图信息
     *
     * @param banner
     * @Param 轮播图信息对象
     */
    @Override
    public void updateBanner(Banner banner) throws Exception {
        //1.检查默认值
        if (banner.getIsActive()==null){
            banner.setIsActive(true);
        }
        if (banner.getSortOrder()==null){
            banner.setSortOrder(5);
        }
        //2.自动填充字段 createTime updateTime is_deleted
        //3.保存banner
        boolean result = updateById(banner);
        if (!result){
            throw new Exception("轮播图信息修改失败");
        }
    }
}